
package com.zhu.salesmanagement;

import java.util.ArrayList;

import com.zhu.location.R;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.models.AddedStoreItemInfo;
import com.zhu.salesmanagement.models.ProductInfo;
import com.zhu.salesmanagement.models.RemindItemInfo;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.views.ObservableScrollView;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

public class RemindListActivity extends Activity implements View.OnClickListener {

	private static final int UPDATECONTENT = 0;

    private final static int REMINDS_LIST_QUERY_TOKEN = 1000;
    private final static int REMINDS_LIST_DELETE_TOKEN = 2000;
    private final static String TAG = "zhu";

    LinearLayout mContentLayout = null;
    private ArrayList<CheckBox> mBoxList = new ArrayList<CheckBox>();;
    private ArrayList<RemindItemInfo> mRemindList = new ArrayList<RemindItemInfo>();
    private TextView mNoneView = null;
    private ObservableScrollView mScrollView;
    private TextView mScollClew = null;
    private RemindsListQueryHandler mRemindsListQueryHandler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_remindlist);
        mRemindsListQueryHandler = new RemindsListQueryHandler(this.getContentResolver());

        setupView();
        initData();
    }

    private void setupView() {
        mScrollView = (ObservableScrollView) findViewById(R.id.remindlist_scroll);
        mScrollView.setScrollViewListener(mScrollViewListener);
        mScollClew = (TextView) findViewById(R.id.visitTask_scrollclew);
        mContentLayout = (LinearLayout) findViewById(R.id.remindlist_content);
        findViewById(R.id.remindlist_bottom_back).setOnClickListener(this);
        findViewById(R.id.remindlist_back).setOnClickListener(this);
        findViewById(R.id.remindlist_delete).setOnClickListener(this);
        mNoneView = (TextView) findViewById(R.id.none_text);
    }

    private void initData() {
        startStoresListAsyncQuery();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v != null) {
            switch (v.getId()) {
                case R.id.remindlist_bottom_back:
                case R.id.remindlist_back:
                    finish();
                    break;
                case R.id.remindlist_delete:
                    deleteItems();
                    break;
                case R.id.reminditem_row:
                    gotoContentActivity((RemindItemInfo) v.getTag());
                    break;
            }
        }
    }

    private void updateContent() {
        mContentLayout.removeAllViews();
        mBoxList.clear();
        for (int i = 0; i < mRemindList.size(); i++) {
            RemindItemInfo info = mRemindList.get(i);
            View v = getRowView(info);
            mContentLayout.addView(v);
        }

        if (mRemindList.size() > 0) {
            mNoneView.setVisibility(View.GONE);
        } else {
            mNoneView.setVisibility(View.VISIBLE);
        }

        mScrollView.post(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                if (mScrollView.canScrollView()) {
                    mScollClew.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private View getRowView(RemindItemInfo info) {
        View row = LayoutInflater.from(this).inflate(R.layout.remindlist_item, null);
        View rowView = row.findViewById(R.id.reminditem_row);
        rowView.setOnClickListener(this);
        rowView.setTag(info);
        CheckBox box = (CheckBox) (row.findViewById(R.id.reminditem_checkbox));
        mBoxList.add(box);
        box.setTag(info);
        TextView title = (TextView) (row.findViewById(R.id.reminditem_title));
        title.setText(info.mName);
        return row;
    }

    private void deleteItems() {
        int deleteCount = 0;
        CheckBox box = null;
        String where = "";
        String eventWhere = "";
        for (int i = 0; i < mBoxList.size(); i++) {
            box = mBoxList.get(i);
            if (box.isChecked()) {
                deleteCount++;
                RemindItemInfo info = (RemindItemInfo) box.getTag();
                if (where.length() == 0) {
                    where += SalesSettings.RemindsColumns._ID + " = " + info.id;
                } else {
                    where += " or " + SalesSettings.RemindsColumns._ID + " = " + info.id;
                }
                if(info.eventId != null && info.eventId.length() > 0){
                    if(eventWhere.length() == 0){
                        eventWhere += SalesSettings.RemindsColumns._ID + " = " + info.eventId;
                    }else{
                        eventWhere += " or " +SalesSettings.RemindsColumns._ID + " = " + info.eventId;
                    }
                }
            }
        }
        if (deleteCount == 0) {
            Actions.toastShort(this, getResources().getString(R.string.seclectdelete));
        } else {
            Actions.deleteEvent(this, eventWhere);
            getContentResolver().delete(SalesSettings.RemindsColumns.CONTENT_URI, where, null);
            Actions.toastShort(this, getResources().getString(R.string.delete_success));
        }
        startStoresListAsyncQuery();
    }

    private void gotoContentActivity(RemindItemInfo info) {
        Intent intent = new Intent(this, RemindContentActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("info", info);
        intent.putExtras(bundle);
        startActivityForResult(intent, UPDATECONTENT);
    }

    private void startStoresListAsyncQuery() {
        try {
            mRemindsListQueryHandler.startQuery(REMINDS_LIST_QUERY_TOKEN, null,
                    SalesSettings.RemindsColumns.CONTENT_URI, null, null, null, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    private ObservableScrollView.ScrollViewListener mScrollViewListener = new ObservableScrollView.ScrollViewListener() {

        @Override
        public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx,
                int oldy) {
            // TODO Auto-generated method stub
            if (Actions.DEBUG) {
                Log.e("zhu", "onScrollChanged=" + Math.abs(y - oldy));
            }
            if (Math.abs(y - oldy) > 1) {
                mScollClew.setVisibility(View.GONE);
            }
        }

    };

    private final class RemindsListQueryHandler extends AsyncQueryHandler {
        public RemindsListQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case REMINDS_LIST_QUERY_TOKEN:
                    updateListData(cursor);
                    break;
                default:
                    Log.e(TAG, "onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {
            switch (token) {
                case REMINDS_LIST_DELETE_TOKEN:
                    break;
                default:
                    Log.e(TAG, "onDeleteComplete called with unknown token " + token);
            }
        }
    }

    private void updateListData(Cursor cursor) {
        mRemindList.clear();
        try {
            final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.RemindsColumns._ID);
            final int textIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.RemindsColumns.TEXT);
            final int timeIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.RemindsColumns.TIME);
            final int typeIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.RemindsColumns.TYPE);
            final int eventIdIndex = cursor
            .getColumnIndexOrThrow(SalesSettings.RemindsColumns.EVENTID);

            while (cursor.moveToNext()) {
                RemindItemInfo info = new RemindItemInfo();
                info.id = cursor.getLong(idIndex);
                info.mName = cursor.getString(textIndex);
                info.mTime = cursor.getString(timeIndex);
                info.mType = cursor.getString(typeIndex);
                info.eventId = cursor.getString(eventIdIndex);
                mRemindList.add(info);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "update Remind ListData error");
        } finally {
            cursor.close();
        }
        updateContent();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		switch (requestCode) {
			case UPDATECONTENT:
				initData();
				break;
		}
	}
}
